<template>
  <div class="user-profile">
    <div class="header">
      <h1>个人中心</h1>
    </div>
    
    <el-card class="profile-card">
      <div class="profile-header">
        <div class="avatar">
          <el-avatar :size="100" :src="userForm.avatar || '/default-avatar.png'"></el-avatar>
          <div class="avatar-upload">
            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="handleAvatarUpload">
              <el-button size="small" type="primary">更换头像</el-button>
            </el-upload>
          </div>
        </div>
        <div class="user-info">
          <h2>{{ userForm.nickname || userForm.username || '用户名' }}</h2>
          <p>{{ userForm.email || 'user@example.com' }}</p>
          <p>手机号: {{ userForm.phone || '未设置' }}</p>
          <p>注册时间: {{ formatDate(userForm.createdAt) }}</p>
        </div>
      </div>
      
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="basic">
          <el-form :model="userForm" label-width="100px" :rules="userFormRules" ref="userFormRef">
            <el-form-item label="用户名">
              <el-input v-model="userForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="userForm.nickname" placeholder="请输入昵称"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userForm.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input v-model="userForm.address" placeholder="请输入地址" type="textarea" :rows="2"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveUserInfo" :loading="savingProfile">保存修改</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="修改密码" name="password">
          <el-form :model="passwordForm" label-width="100px" :rules="passwordRules" ref="passwordFormRef">
            <el-form-item label="原密码" prop="oldPassword">
              <el-input v-model="passwordForm.oldPassword" type="password" show-password></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="changePassword" :loading="changingPassword">修改密码</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="我的订单" name="orders">
          <div class="order-stats">
            <el-row :gutter="20">
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-value">{{ orderStats.total || 0 }}</div>
                  <div class="stat-label">全部订单</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-value">{{ orderStats.pendingPayment || 0 }}</div>
                  <div class="stat-label">待付款</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-value">{{ orderStats.pendingDelivery || 0 }}</div>
                  <div class="stat-label">待发货</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-value">{{ orderStats.pendingReceive || 0 }}</div>
                  <div class="stat-label">待收货</div>
                </div>
              </el-col>
            </el-row>
          </div>
          
          <div class="order-list">
            <h3>最近订单</h3>
            <el-table :data="recentOrders" style="width: 100%" v-loading="loadingOrders">
              <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
              <el-table-column prop="createdAt" label="下单时间" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.createdAt) }}
                </template>
              </el-table-column>
              <el-table-column prop="totalAmount" label="订单金额">
                <template #default="{ row }">
                  ¥{{ row.totalAmount?.toFixed(2) || '0.00' }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态">
                <template #default="{ row }">
                  <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button size="small" @click="viewOrderDetail(row.id)">查看详情</el-button>
                  <el-button size="small" v-if="row.status === 1 || row.status === 'PENDING_PAYMENT'" @click="cancelOrder(row.id)">取消订单</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <div class="order-actions">
            <el-button type="primary" @click="goToOrders">查看所有订单</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../store'
import { userService } from '../services/authService'
import { orderService } from '../services/orderService'

const router = useRouter()
const userStore = useUserStore()

// 当前激活的标签页
const activeTab = ref('basic')

// 加载状态
const savingProfile = ref(false)
const changingPassword = ref(false)
const loadingOrders = ref(false)

// 用户表单
const userForm = reactive({
  id: '',
  username: '',
  nickname: '',
  email: '',
  phone: '',
  avatar: '',
  createdAt: '',
  address: ''
})

// 用户表单验证规则
const userFormRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码验证规则
const passwordRules = {
  oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 订单统计
const orderStats = reactive({
  total: 0,
  pendingPayment: 0,
  pendingDelivery: 0,
  pendingReceive: 0
})

// 最近订单列表
const recentOrders = ref([])

// 格式化日期
const formatDate = (date) => {
  if (!date) return '未知'
  return new Date(date).toLocaleDateString('zh-CN')
}

// 获取订单状态类型
const getStatusType = (status) => {
  // 处理数字状态码
  const numericStatus = parseInt(status)
  if (!isNaN(numericStatus)) {
    const types = {
      0: 'warning',    // 待付款
      1: 'info',       // 待发货
      2: 'primary',    // 待收货
      3: 'success',    // 已完成
      4: 'danger',     // 已取消
      5: 'danger',     // 退款中
      6: 'danger'      // 已退款
    }
    return types[numericStatus] || 'info'
  }
  
  // 处理字符串状态
  const types = {
    'PENDING_PAYMENT': 'warning',
    'PENDING_DELIVERY': 'info',
    'PENDING_RECEIVE': 'primary',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  }
  return types[status] || 'info'
}

// 获取订单状态文本
const getStatusText = (status) => {
  // 处理数字状态码
  const numericStatus = parseInt(status)
  if (!isNaN(numericStatus)) {
    const texts = {
      0: '待付款',
      1: '待发货',
      2: '待收货',
      3: '已完成',
      4: '已取消',
      5: '退款中',
      6: '已退款'
    }
    return texts[numericStatus] || '未知'
  }
  
  // 处理字符串状态
  const texts = {
    'PENDING_PAYMENT': '待付款',
    'PENDING_DELIVERY': '待发货',
    'PENDING_RECEIVE': '待收货',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return texts[status] || '未知'
}

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理头像上传
const handleAvatarUpload = async (options) => {
  try {
    // 模拟上传过程，实际项目中应该调用文件上传API
    ElMessage.info('头像上传中...')
    
    // 模拟上传延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 生成模拟头像URL
    const avatarUrl = `https://api.dicebear.com/7.x/avataaars/svg?seed=${Date.now()}`
    
    // 优先使用id，如果没有则使用userId，并确保转换为字符串
const userId = String(userForm.id || userStore.userInfo.id || userStore.userInfo.userId || '')
console.log('准备更新头像，用户ID:', userId)

// 确保用户ID有效
if (!userId) {
    ElMessage.error('用户ID无效，无法更新头像')
    return
}

// 确保使用正确的用户ID格式调用API
const response = await userService.updateAvatar(userId, avatarUrl)
    
    if (response) {
      userForm.avatar = avatarUrl
      userStore.updateUserInfo({ ...userStore.userInfo, avatar: avatarUrl })
      ElMessage.success('头像更新成功')
    }
  } catch (error) {
    ElMessage.error('头像上传失败，请重试')
  }
}

// 保存用户信息
const saveUserInfo = async () => {
  try {
    savingProfile.value = true
    
    // 验证表单
    if (!userForm.email) {
      ElMessage.error('邮箱不能为空')
      return
    }
    
    if (userForm.phone && !/^1[3-9]\d{9}$/.test(userForm.phone)) {
      ElMessage.error('请输入正确的手机号')
      return
    }
    
    const profileData = {
      email: userForm.email.trim(),
      phone: userForm.phone ? userForm.phone.trim() : null,
      nickname: userForm.nickname ? userForm.nickname.trim() : null,
      avatar: userForm.avatar || null,
      address: userForm.address ? userForm.address.trim() : null
    }
    
    // 优先使用id，如果没有则使用userId，并确保转换为字符串
const userId = String(userForm.id || userStore.userInfo.id || userStore.userInfo.userId || '')
console.log('准备保存用户信息，用户ID:', userId)
console.log('保存的用户数据:', profileData)

// 确保用户ID有效
if (!userId) {
    ElMessage.error('用户ID无效，无法保存用户信息')
    return
}

// 确保使用正确的用户ID格式调用API
const response = await userService.updateProfile(userId, profileData)
    
    console.log('保存用户信息的响应:', response)
    
    if (response) {
      // 更新本地用户信息
      userStore.updateUserInfo({
        ...userStore.userInfo,
        email: userForm.email,
        phone: userForm.phone,
        nickname: userForm.nickname,
        avatar: userForm.avatar,
        address: userForm.address
      })
      
      ElMessage.success('用户信息保存成功')
    } else {
      ElMessage.error('保存失败，服务器无响应')
    }
  } catch (error) {
    console.error('保存用户信息失败:', error)
    ElMessage.error('保存失败: ' + (error.message || '请检查输入信息是否正确'))
  } finally {
    savingProfile.value = false
  }
}

// 修改密码
const changePassword = async () => {
  try {
    changingPassword.value = true
    
    // 验证密码输入
    if (!passwordForm.oldPassword || !passwordForm.newPassword || !passwordForm.confirmPassword) {
      ElMessage.error('请填写所有密码字段')
      return
    }
    
    if (passwordForm.newPassword !== passwordForm.confirmPassword) {
      ElMessage.error('新密码和确认密码不一致')
      return
    }
    
    if (passwordForm.newPassword.length < 6) {
      ElMessage.error('新密码长度不能少于6位')
      return
    }
    
    const passwordData = {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
      confirmPassword: passwordForm.confirmPassword
    }
    
    // 优先使用id，如果没有则使用userId，并确保转换为字符串
    const userId = String(userForm.id || userStore.userInfo.id || userStore.userInfo.userId || '')
    console.log('准备修改密码，用户ID:', userId)
    
    // 确保用户ID有效
    if (!userId) {
        ElMessage.error('用户ID无效，无法修改密码')
        return
    }
    
    console.log('密码数据:', { oldPassword: passwordData.oldPassword ? '***' : '空', newPassword: passwordData.newPassword ? '***' : '空' })
    
    // 确保使用正确的用户ID格式调用API
    const response = await userService.changePassword(userId, passwordData)
    
    console.log('修改密码的响应:', response)
    
    if (response) {
      ElMessage.success('密码修改成功')
      
      // 清空表单
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    } else {
      ElMessage.error('密码修改失败，服务器无响应')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('密码修改失败: ' + (error.message || '请检查原密码是否正确'))
  } finally {
    changingPassword.value = false
  }
}

// 查看订单详情
const viewOrderDetail = (orderId) => {
  router.push(`/order/${orderId}`)
}

// 取消订单
const cancelOrder = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '取消订单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await orderService.cancelOrder(orderId)
    
    if (response) {
      ElMessage.success('订单取消成功')
      // 重新加载订单数据
      loadOrderData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消订单失败，请重试')
    }
  }
}

// 跳转到订单列表
const goToOrders = () => {
  router.push('/orders')
}

// 加载用户信息
const loadUserInfo = async () => {
  try {
    // 确保用户信息已加载
    if (!userStore.userInfo) {
      console.warn('用户信息不存在，尝试从localStorage加载')
      await userStore.loadUserInfo()
    }
    
    if (userStore.userInfo && (userStore.userInfo.id || userStore.userInfo.userId)) {
      // 优先使用id，如果没有则使用userId，并确保转换为字符串
      const userId = String(userStore.userInfo.id || userStore.userInfo.userId || '')
      console.log('开始加载用户信息，用户ID:', userId, '用户信息:', userStore.userInfo)
      
      // 确保用户ID有效
      if (!userId) {
        console.warn('用户ID无效，无法加载用户信息')
        ElMessage.warning('用户信息加载失败，请重新登录')
        return
      }
      
      // 确保使用正确的用户ID格式调用API
      try {
        const response = await userService.getUserProfile()
        
        console.log('用户信息响应:', response)
        
        if (response && response.data) {
          const userData = response.data
          console.log('用户数据:', userData)
          
          // 确保正确处理字段映射，添加容错处理
          Object.assign(userForm, {
            id: userData.id || userId,
            username: userData.username || userStore.userInfo.username || '未知用户',
            nickname: userData.nickname || userData.username || userStore.userInfo.nickname || userStore.userInfo.username || '未知用户',
            email: userData.email || userStore.userInfo.email || '',
            phone: userData.phone || userStore.userInfo.phoneNumber || '',
            avatar: userData.avatar || userStore.userInfo.avatarUrl || '',
            createdAt: userData.createdAt || userStore.userInfo.createdAt || '',
            address: userData.address || userStore.userInfo.address || ''
          })
          
          console.log('更新后的用户表单:', userForm)
        } else if (response) {
          // 如果直接返回用户数据（不是包装在data中）
          const userData = response
          console.log('直接返回的用户数据:', userData)
          
          Object.assign(userForm, {
            id: userData.id || userId,
            username: userData.username || userStore.userInfo.username || '未知用户',
            nickname: userData.nickname || userData.username || userStore.userInfo.nickname || userStore.userInfo.username || '未知用户',
            email: userData.email || userStore.userInfo.email || '',
            phone: userData.phone || userStore.userInfo.phoneNumber || '',
            avatar: userData.avatar || userStore.userInfo.avatarUrl || '',
            createdAt: userData.createdAt || userStore.userInfo.createdAt || '',
            address: userData.address || userStore.userInfo.address || ''
          })
          
          console.log('更新后的用户表单:', userForm)
        } else {
          console.warn('用户信息响应为空或格式不正确')
          // 使用store中的用户信息作为后备
          if (userStore.userInfo) {
            Object.assign(userForm, {
              id: userId,
              username: userStore.userInfo.username || '未知用户',
              nickname: userStore.userInfo.nickname || userStore.userInfo.username || '未知用户',
              email: userStore.userInfo.email || '',
              phone: userStore.userInfo.phoneNumber || '',
              avatar: userStore.userInfo.avatarUrl || '',
              createdAt: userStore.userInfo.createdAt || ''
            })
          }
        }
      } catch (apiError) {
        console.error('调用用户信息API失败:', apiError)
        // 如果API调用失败，使用store中的用户信息作为后备
        if (userStore.userInfo) {
          const userId = userStore.userInfo.id || userStore.userInfo.userId
          Object.assign(userForm, {
            id: userId,
            username: userStore.userInfo.username || '未知用户',
            nickname: userStore.userInfo.nickname || userStore.userInfo.username || '未知用户',
            email: userStore.userInfo.email || '',
            phone: userStore.userInfo.phoneNumber || '',
            avatar: userStore.userInfo.avatarUrl || '',
            createdAt: userStore.userInfo.createdAt || '',
            address: userStore.userInfo.address || ''
          })
          ElMessage.warning('获取最新用户信息失败，显示缓存信息')
        }
      }
    } else {
      console.warn('用户store中没有用户信息或用户ID')
      console.log('当前用户store状态:', userStore)
    }
  } catch (error) {
    console.error('加载用户信息失败:', error)
    ElMessage.error('加载用户信息失败: ' + (error.message || '未知错误'))
    
    // 出错时仍然尝试使用store中的用户信息
    if (userStore.userInfo) {
      const userId = userStore.userInfo.id || userStore.userInfo.userId
      Object.assign(userForm, {
        id: userId,
        username: userStore.userInfo.username || '未知用户',
        nickname: userStore.userInfo.nickname || userStore.userInfo.username || '未知用户',
        email: userStore.userInfo.email || '',
        phone: userStore.userInfo.phoneNumber || '',
        avatar: userStore.userInfo.avatarUrl || '',
        createdAt: userStore.userInfo.createdAt || '',
        address: userStore.userInfo.address || ''
      })
    }
  }
}

// 加载订单数据
const loadOrderData = async () => {
  try {
    loadingOrders.value = true
    
    if (userStore.userInfo && (userStore.userInfo.id || userStore.userInfo.userId)) {
      // 优先使用id，如果没有则使用userId，并确保转换为字符串
      const userId = String(userStore.userInfo.id || userStore.userInfo.userId || '')
      console.log('开始加载订单数据，用户ID:', userId)
      
      // 确保用户ID有效
      if (!userId) {
        console.warn('用户ID无效，无法加载订单数据')
        // 使用模拟数据作为后备
        recentOrders.value = [
          {
            id: 1,
            orderNo: 'ORD20241201001',
            createTime: '2024-12-01 10:30:00',
            totalAmount: '¥299.00',
            status: 'COMPLETED'
          },
          {
            id: 2,
            orderNo: 'ORD20241202001',
            createTime: '2024-12-02 14:20:00',
            totalAmount: '¥158.00',
            status: 'PENDING_DELIVERY'
          }
        ]
        orderStats.total = 12
        orderStats.pendingPayment = 2
        orderStats.pendingDelivery = 1
        orderStats.pendingReceive = 3
        return
      }
      
      // 使用正确的接口调用 - 调用无参数的订单列表接口，用户ID由后端从认证信息获取
      // 个人中心需要获取所有订单来做统计，所以使用较大的页面大小
      // 注意：后端使用0-based分页，所以第一页传0
      const response = await orderService.getUserOrders(0, 100)
      console.log('订单数据响应:', response)
      console.log('响应类型:', typeof response)
      console.log('响应结构:', JSON.stringify(response, null, 2))
      
      let orders = []
      
      // 处理不同的响应格式
      if (response && response.orders) {
        // 如果响应是 { orders: [...], total: ... } 格式
        orders = response.orders || []
      } else if (Array.isArray(response)) {
        // 如果直接返回数组
        orders = response
      } else if (response && Array.isArray(response.data)) {
        // 如果响应是 { data: [...] } 格式
        orders = response.data
      } else {
        // 其他情况，尝试从响应中提取订单数据
        orders = response || []
      }
      
      console.log('处理后的订单数据:', orders)
      recentOrders.value = orders.slice(0, 5) // 只显示最近5个订单
      
      // 计算订单统计
      orderStats.total = orders.length
      orderStats.pendingPayment = orders.filter(o => o.status === 0 || o.status === 'PENDING_PAYMENT' || o.status === 'PENDING').length
      orderStats.pendingDelivery = orders.filter(o => o.status === 1 || o.status === 'PENDING_DELIVERY' || o.status === 'PAID').length
      orderStats.pendingReceive = orders.filter(o => o.status === 2 || o.status === 'PENDING_RECEIVE' || o.status === 'SHIPPED').length
    } else {
      console.warn('用户store中没有用户信息或用户ID')
      console.log('当前用户store状态:', userStore)
      // 没有用户信息时不显示订单数据
      recentOrders.value = []
      orderStats.total = 0
      orderStats.pendingPayment = 0
      orderStats.pendingDelivery = 0
      orderStats.pendingReceive = 0
    }
  } catch (error) {
    console.error('加载订单数据失败:', error)
    // 加载失败时不显示模拟数据，清空订单列表
    recentOrders.value = []
    orderStats.total = 0
    orderStats.pendingPayment = 0
    orderStats.pendingDelivery = 0
    orderStats.pendingReceive = 0
  } finally {
    loadingOrders.value = false
  }
}

// 页面加载时初始化数据
onMounted(async () => {
  await loadUserInfo()
  await loadOrderData()
})
</script>

<style scoped>
.user-profile {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  margin-bottom: 30px;
}

.header h1 {
  font-size: 28px;
  color: #333;
}

.profile-card {
  margin-bottom: 20px;
}

.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.avatar {
  margin-right: 30px;
  text-align: center;
}

.avatar-upload {
  margin-top: 10px;
}

.user-info h2 {
  font-size: 24px;
  margin-bottom: 10px;
  color: #333;
}

.user-info p {
  color: #666;
  font-size: 16px;
  margin-bottom: 5px;
}

.order-stats {
  margin-bottom: 30px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
  transition: all 0.3s;
}

.stat-item:hover {
  background-color: #e8f4fd;
  transform: translateY(-2px);
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 10px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.order-list {
  margin-bottom: 30px;
}

.order-list h3 {
  margin-bottom: 20px;
  color: #333;
}

.order-actions {
  text-align: center;
}

.el-button {
  margin-right: 10px;
}
</style>